package com.xiaoyi.common.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoyi.entity.ResultBody;
import com.xiaoyi.entity.SysMenu;
import com.xiaoyi.entity.SysRole;
import com.xiaoyi.entity.SysUser;
import com.xiaoyi.service.SysMenuService;
import com.xiaoyi.service.SysRoleService;
import com.xiaoyi.service.SysUserService;
import com.xiaoyi.util.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 小易
 * @version 1.0
 * @description TODO 登录成功处理器
 * @date 2022/12/6 15:09
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private SysUserService userService;

    @Resource
    private SysRoleService roleService;

    @Resource
    private SysMenuService menuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        // 生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", authentication.getName());
        String token = JwtUtils.createToken(map);
        // 获取用户信息
        SysUser currentUser = userService.getByUsername(authentication.getName());
        // 获取用户权限菜单
        List<SysRole> roleList = roleService.list(new QueryWrapper<SysRole>().inSql("id", "SELECT role_id FROM sys_user_role WHERE user_id = " + currentUser.getId()));
        // 去重
        Set<SysMenu> menuSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> menuList = menuService.list(new QueryWrapper<SysMenu>().inSql("id", "SELECT menu_id FROM sys_role_menu WHERE role_id = " + sysRole.getId()));
            menuSet.addAll(menuList);
        }
        // 排序
        ArrayList<SysMenu> sysMenus = new ArrayList<>(menuSet);
        sysMenus.sort(Comparator.comparing(SysMenu::getOrderNum));
        // 存在父级和子级关系,需要处理

        List<SysMenu> menuList = menuService.buildTreeMenu(sysMenus);

        currentUser.setRoles(roleList.stream().map(SysRole::getName).collect(Collectors.joining(",")));

        // 组装返回对象
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("currentUser", currentUser);
        result.put("menuList", menuList);
        outputStream.write(JSON.toJSONString(ResultBody.success(result)).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
